package com.young.mybatisdiy.config;

import com.github.pagehelper.PageHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * 数据库相关配置
 * 包括：
 * 1：PageHelper 开启分页
 * 2：启动过程数据库配置检查 配置信息无效 终止启动
 *
 * @author ：<a href="mailto:youngkun2016@163.com">young</a>
 * @date ：Created in 2020/4/13
 */
@Configuration
@MapperScan("com.young.mybatisdiy.mapper")
public class DataSourceConfig implements ApplicationContextAware {

    private static Logger logger = LogManager.getLogger(DataSourceConfig.class);

    private static ApplicationContext context;

    /**
     * Spring Boot 可以采用
     * 这种方式配置PageHelper Bean
     *
     * @return
     */
    @Bean
    public PageHelper getPageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("helperDialect", "mysql");
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        return pageHelper;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        try {
            context = applicationContext;
            // ===== 在项目初始化bean后检验数据库连接是否
            DataSource dataSource = (DataSource) context.getBean("dataSource");
            dataSource.getConnection().close();
        } catch (Exception e) {
            logger.error("数据库配置异常", e.getMessage());
            // ===== 当检测数据库连接失败时, 停止项目启动
            System.exit(-1);
        }
    }
}